<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>成绩汇总</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片搜索图表 -->
    <el-card v-loading="loading">
      <div>
        <el-button type="primary" @click="exportExcel">导出</el-button>
      </div>

      <el-table :data="table_data" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column prop="user_name" label="姓名"></el-table-column>
        <el-table-column prop="value" label="总分值"></el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="search"
        :current-page.sync="searchForm.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchForm.page_size"
        layout="total, sizes, prev, pager, next"
        :total="count"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      searchForm: {
        page_no: 1,
        page_size: 10,
        search: {
          user_name: ''
        }
      },
      table_data: [],
      count: 0
    };
  },
  mounted: function() {
    this.search();
  },
  methods: {
    search: async function() {
      this.loading = true;
      const { data: resp } = await this.$http.post(
        'score/summary',
        this.searchForm
      );
      this.loading = false;
      if (resp.code === 0) {
        this.table_data = resp.data;
        this.count = resp.count;
      } else {
        this.$message({
          showClose: true,
          message: resp.msg,
          center: true,
          type: 'error'
        });
      }
    },
    exportExcel: function() {
      require.ensure([], () => {
        const {
          exportJson2excel
        } = require('../../assets/js/excel/Export2Excel');

        const tHeader = ['姓名', '总分值'];
        // 上面设置Excel的表格第一行的标题
        const filterVal = ['user_name', 'value'];
        // 上面的index、nickName、name是tableData里对象的属性
        const list = this.table_data;
        // 把data里的tableData存到list
        const data = this.formatJson(filterVal, list);
        exportJson2excel(tHeader, data, '成绩汇总');
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    handleSizeChange: function(newPageSize) {
      this.searchForm.page_size = newPageSize;
      this.search();
    },
    handleCurrentChange: function() {}
  }
};
</script>
